#!/usr/bin/perl
# 2013/05/08 Make association map for ChIA-PET


use strict;
use warnings;
use IO::File;
use Getopt::Std;
use File::Basename;
use Carp qw(croak);
$| = 0;


if(@ARGV != 6 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [map file] -o [output association file] -r [resolution]\n";
}

my %opt;
getopts("i:r:o:", \%opt);
my $FILE_map = $opt{i};
my $Resolution = $opt{r};
my $FILE_out = $opt{o};


my %Len_chr = (
	'I'	=>	5579133,
	'II'	=>	4539804,
	'III'	=>	2452883,
);



#---------------------------------------
# correct information
#---------------------------------------
my %data;
my $fh_map = IO::File->new($FILE_map) or die "cannot open $FILE_map: $!";
while($_ = $fh_map->getline()){
	s/\r?\n//;
	my ($id, $chr1, $loc1, $direction1, $mapQ1, $hinID1, $hinLoc1, $chr2, $loc2, $direction2, $mapQ2, $hinID2, $hinLoc2, $type, $num, $locations) = split /\t/;

	my $cate1 = int($hinLoc1 / $Resolution) * $Resolution + 1;
	my $cate1_end = $cate1 + $Resolution - 1;
	my $cate2 = int($hinLoc2 / $Resolution) * $Resolution + 1;
	my $cate2_end = $cate2 + $Resolution - 1;

	my $bin1 = "$chr1:$cate1-$cate1_end";
	my $bin2 = "$chr2:$cate2-$cate2_end";

	my $hinNum1 = substr($hinID1, 0, -1);
	my $hinNum2 = substr($hinID2, 0, -1);

	if($hinNum1 < $hinNum2){
		$data{$bin1}{$bin2}++;
	}else{
		$data{$bin2}{$bin1}++;
	}
}
$fh_map->close();


#---------------------------------------
# register bins
#---------------------------------------
my @binLists;
foreach my $chr(qw(I II III)){
	for(my $i = 1; $i < $Len_chr{$chr}; $i += $Resolution){
		my $end = $i + $Resolution - 1;
		push @binLists, "$chr:$i-$end";
	}
}


#---------------------------------------
# output
#---------------------------------------
my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
for(my $i = 0; $i < @binLists; $i++){
	my $bin1 = $binLists[$i];
	for(my $j = 0; $j < @binLists; $j++){
		my $bin2 = $binLists[$j];
		my $value = 0;
		if($i < $j){
			$value = exists $data{$bin1}{$bin2} ? $data{$bin1}{$bin2} : 0;
		}else{
			$value = exists $data{$bin2}{$bin1} ? $data{$bin2}{$bin1} : 0;
		}
		$fh_out->print("$bin1\t$bin2\t$value\n");
	}
}
$fh_out->close();

